from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth import get_user_model

User = get_user_model()

class PasswordResetView(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request, *args, **kwargs):
        old_password = request.data.get('oldPassword')
        new_password = request.data.get('password')
        new_password2 = request.data.get('password2')

        user = request.user

        # 1. 检查所有密码字段是否提供
        if not old_password or not new_password or not new_password2:
            return Response(
                {"detail": "请填写所有密码字段。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 验证新密码和确认密码是否一致
        if new_password != new_password2:
            return Response(
                {"detail": "两次输入的新密码不一致。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 3. 验证原密码是否正确
        if not user.check_password(old_password):
            return Response(
                {"detail": "原密码不正确。"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 4. 密码不能与旧密码相同
        if user.check_password(new_password):
            return Response(
                {"detail": "新密码不能与原密码相同。"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 5. 更新密码
        user.set_password(new_password)
        user.save()

        return Response(
            {"detail": "密码修改成功！"},
            status=status.HTTP_200_OK
        ) 